#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>

using namespace std;

vector<vector<int>> threeSum(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> res;

    for (int i = 0; i < nums.size(); i++)
    {
        if (i > 0 && nums[i] == nums[i - 1]) continue;
        int l = i + 1, r = nums.size() - 1;
        while (l < r)
        {
            int sum = nums[l] + nums[r];
            if (sum == -nums[i])
            {
                res.push_back({ nums[i],nums[l],nums[r] });
                l++, r--;
                while (l < r && nums[l] == nums[l - 1]) l++;
                while (l < r && nums[r] == nums[r + 1]) r--;
            }
            else if (sum < -nums[i]) l++;
            else r--;
        }
    }
    return res;
}

struct ListNode {
    int val;
    struct ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

stack<int> cnt(ListNode* root)
{
    stack<int> stk;
    while (root)
    {
        stk.push(root->val);
        root = root->next;
    }
    return stk;
}

ListNode* get(string res)
{
    stack<ListNode*> stk;
    for (auto it : res)
    {
        auto root = new ListNode(it - '0');
        stk.push(root);
    }

    ListNode* prev = nullptr;
    while (stk.size())
    {
        auto t = stk.top();
        stk.pop();
        t->next = prev;
        prev = t;
    }
    return prev;
}

ListNode* addInList(ListNode* head1, ListNode* head2) {
    auto s1 = cnt(head1);
    auto s2 = cnt(head2);
    string res;
    int prev = 0;

    while (s1.size() || s2.size() || prev)
    {
        int l = 0, r = 0;
        if (s1.size())
        {
            l = s1.top();
            s1.pop();
        }
        if (s2.size())
        {
            r = s2.top();
            s2.pop();
        }

        int t = l + r + prev;
        prev = t / 10;
        t %= 10;
        res += (t + '0');
    }

    reverse(res.begin(), res.end());
    return get(res);
}